package angry.courses.servlets;

import angry.courses.database.ICoursesDB;

import java.io.PrintWriter;

import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import javax.servlet.ServletException;

public class RemoveCourseServlet extends HttpServlet {
    private ICoursesDB coursesDB;
    
    public void init() throws ServletException {
	coursesDB = (ICoursesDB) getServletContext().getAttribute("coursesDB");
    }

    public void destroy() {
	coursesDB = null;
    }

    public void doGet(HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException {
	res.setContentType("text/html");

	final List<String> courseNames = coursesDB.getCourseNames();

	PrintWriter out = res.getWriter();
	out.println(new HtmlFormatter() {

	    public String title() {
		return "Remove Course";
	    }

	    public void body(StringBuffer buf) {
		if (courseNames.size() > 0) {
		    form(buf);
		} else {
		    buf.append("No courses exist at the moment.<br>");
		    buf.append("Click " + link("here", "admin.html") +
			       " to go back.");
		}
	    }

	    public void form(StringBuffer buf) {
		buf.append(heading(3, "Select the course: "));
		buf.append("<form method=\"post\" action=\"RemoveCourse\" >");
		buf.append(dropdown("course", "", courseNames));
		buf.append(" " +  button("Delete"));
		buf.append("</form>");
	    }
        }.htmlTag());
	out.close();
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException {
	final String course = req.getParameter("course");
	
	coursesDB.removeCourse(course);

	res.setContentType("text/html");
	PrintWriter out = res.getWriter();
	out.println(new HtmlFormatter() {
	    public String title() {
		return "Course removed";
	    }

   	   public void body(StringBuffer buf) {
	       buf.append(heading(3, "Completed"));
	       buf.append("Removed course \"" + course + "\".<br>");
	       buf.append("Click " + link("here", "admin.html") +
			  " to go back.");
	   }
	}.htmlTag());
	out.close();
    }
}
